package co.salehi.domain;

import javax.persistence.Column;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

import co.salehi.util.Util;
import co.salehi.validation.CheckPasswords;

@RooJavaBean
@RooToString
@RooEntity
@CheckPasswords
@NamedQuery(name = "findByUserName", query = "select p from Operator p where p.userName=:uName")
public class Operator {

	@NotNull
    private String firstName;

	@NotNull
    private String lastName;

	@NotNull
	@Column(unique = true)
    private String userName;

	@NotNull
    private String password;

	@NotNull
	@Transient
    private String password2;

    private Boolean enabled = true;

    @NotNull
    @Value("ROLE_USER")
    private String authority;
    
	@Transactional
	public void persist() {
		if (this.entityManager == null)
			this.entityManager = entityManager();
		encryptPassword(this);
		this.entityManager.persist(this);
	}

	public void encryptPassword(Operator merged) {
		merged.password = Util.toSHA256(password);
		merged.password2 = Util.toSHA256(password2);
	}


    public static Operator findOperator(String userName) {
        Query findByUserNameQuery = entityManager().createNamedQuery("findByUserName");
        return (Operator)findByUserNameQuery.setParameter("uName", userName).getSingleResult();
    }
    
    @Transactional
    public Operator merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        encryptPassword(this);
        Operator merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

}
